package threads;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import domain.ServerDomainController;

public class SendPlaylistOnRequestThread extends Thread {
	
	private ServerDomainController dc;
	private DatagramSocket datagramSocket;
	private byte[] buffer;
	private DatagramPacket inPacket;
	private DatagramPacket outPacket;
	private static final int PORT = 4445;

	public SendPlaylistOnRequestThread(ServerDomainController dc){
		super("sendPlaylistOnRequest");
		this.dc = dc;
	}

	@Override
	public void run() {
		super.run();
		while(true){
			try{
				datagramSocket = new DatagramSocket(PORT);
				buffer = new byte[256];
				inPacket = new DatagramPacket(buffer, buffer.length);
				datagramSocket.receive(inPacket);
				
				InetAddress clientAddress = inPacket.getAddress();
				int clientPort = inPacket.getPort();
				
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(new BufferedOutputStream(baos));
				oos.flush();
				oos.writeObject(dc.getSongs());
				oos.flush();
				
				outPacket = new DatagramPacket(baos.toByteArray(), baos.size(), clientAddress, clientPort);
				datagramSocket.send(outPacket);
				datagramSocket.close();
				
			}catch (IOException e) {
				System.out.println("IOException on send playlist: " + e.getMessage());
			}
		}
	}
	
	

}
